package com.forte.demo.robot.timetask;

import com.forte.demo.robot.db.heap.DeleteHeapIgnore;
import com.forte.demo.robot.db.heap.InsertHeapIgnore;
import com.forte.demo.robot.expection.NotBanListInputException;
import com.forte.qqrobot.anno.Constr;
import com.forte.qqrobot.anno.Filter;
import com.forte.qqrobot.anno.Listen;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.beans.messages.msgget.MsgGet;
import com.forte.qqrobot.beans.messages.types.MsgGetTypes;
import com.forte.qqrobot.beans.types.KeywordMatchType;
import com.forte.qqrobot.sender.MsgSender;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.forte.demo.robot.System.heapIgnore;
import static com.forte.demo.robot.db.ban.InputBanList.*;
import static com.forte.demo.robot.db.ban.SelectBanList.selectOthorInputBanGroup;
import static com.forte.demo.robot.db.ban.SelectBanList.selectOthorInputBanQq;
import static com.forte.demo.robot.db.heap.InsertReviewed.insertReviewed;
import static org.apache.commons.lang.StringUtils.isNumeric;

/**
 * @author SitaNya
 * 日期: 2019-06-15
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明: 总监听入口类，这里是实际上接收到消息的第一个类
 */
public class Listener {
    Pattern isId = Pattern.compile("^本人了解退群、关闭等指令，并已知可能导致拉黑的所有操作，现为【(\\d{4,15})】群进行申请");
    Pattern warnning = Pattern.compile("^\\{[\\w\\W]*?},$");
    Pattern groupIdRex = Pattern.compile("^[.。][ ]*ban[ ]*rm[ ]*group[ ]*(\\d{4,15})");
    Pattern qqIdRex = Pattern.compile("^[.。][ ]*ban[ ]*rm[ ]*user[ ]*(\\d{4,15})");

    private static Logger log = LogManager.getLogger(Listener.class.getName());

    private Listener() {
    }

    @Constr
    public static Listener getInstance() {
        return new Listener();
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "^[.。][ ]*ignore[ ]*\\d+")
    public void listenerInputIgnore(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        try {
            String botId = msgGet.getMsg().replaceAll("\\.ignore[ ]*", "").trim();
            new InsertHeapIgnore().insertHeapIgnore(botId);
            msgSender.SENDER.sendGroupMsg("808619122", "已将" + botId + "加入心跳检测忽略名单");
        } catch (NullPointerException e) {
            log.error(e.getMessage(), e);
            log.error(msgGet.getMsg());
        }
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "^[.。][ ]*ignore[ ]*remove[ ]*\\d+")
    public void listenerRemoveIgnore(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        String botId = msgGet.getMsg().replaceAll("\\.ignore[ ]*remove[ ]*", "").trim();
        new DeleteHeapIgnore().deleteHeapIgnore(botId);
        msgSender.SENDER.sendGroupMsg("808619122", "已将" + botId + "移出心跳检测忽略名单");
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "^[.。][ ]*ignore[ ]*show[ ]*")
    public void listenerGetIgnore(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        StringBuilder stringBuilder = new StringBuilder()
                .append("当前心跳检测忽略名单");
        for (String ignorebotId : heapIgnore) {
            stringBuilder.append("\n")
                    .append(ignorebotId);
        }
        msgSender.SENDER.sendGroupMsg("808619122", stringBuilder.toString());
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "^[.。][ ]*ban[ ]*rm[ ]*group[ ]*\\d{4,15}")
    public void listenerRmBanGroupFromShiki(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        if ("2308941253".equals(msgGroup.getQQ())) {
            Matcher matcher = groupIdRex.matcher(msgGet.getMsg());
            while (matcher.find()) {
                String partition = matcher.group(1);
                try {
                    String inputQq = selectOthorInputBanGroup(partition, msgSender, msgGroup);
                    if (inputQq == null) {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "黑名单中无此群组");
                        return;
                    }
                    if (isNumeric(partition) && "2694900224".equals(inputQq)) {
                        deleteGroupBanList(partition);
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已收到来自辉夜的指令，移除群组: " + partition + " 的黑名单条目");
                    } else if (!"2694900224".equals(inputQq)) {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "此黑名单录入人为: " + inputQq);
                    } else {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已收到来自辉夜的指令，但识别错误");
                    }
                } catch (NotBanListInputException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "^[.。][ ]*ban[ ]*rm[ ]*user[ ]*\\d{4,15}")
    public void listenerRmBanUserFromShiki(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        if ("2308941253".equals(msgGroup.getQQ())) {
            Matcher matcher = qqIdRex.matcher(msgGet.getMsg());
            while (matcher.find()) {
                String partition = matcher.group(1);
                try {
                    String inputQq = selectOthorInputBanQq(partition, msgSender, msgGroup);
                    if (inputQq == null) {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "黑名单中无此用户");
                        return;
                    }
                    if (isNumeric(partition) && "2694900224".equals(inputQq)) {
                        deleteQqBanList(partition);
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已收到来自辉夜的指令，移除用户: " + partition + " 的黑名单条目");
                    } else if (!"2694900224".equals(inputQq)) {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "此黑名单录入人为: " + inputQq);
                    } else {
                        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已收到来自辉夜的指令，但识别错误");
                    }
                } catch (NotBanListInputException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Listen(MsgGetTypes.groupMsg)
    @Filter(value = "本人了解退群、关闭等指令，并已知可能导致拉黑的所有操作，现为【\\d{4,15}】群进行申请")
    public void inputReviewed(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        Matcher isIdMatcher = isId.matcher(msgGet.getMsg());
        if (isIdMatcher.find() && isIdMatcher.groupCount() == 1) {
            insertReviewed(Long.parseLong(msgGroup.getQQCode()), Long.parseLong(isIdMatcher.group(1)));
            msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已将群: " + Long.parseLong(isIdMatcher.group(1)) + "录入审核列表，申请人为: " + Long.parseLong(msgGroup.getQQCode()));
            return;
        }
        msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "您的申请格式有误，请按照以下格式（xxxx处为qq号和群号）:\n本人【xxxxx】了解退群、关闭等指令，并已知可能导致拉黑的所有操作，现为【xxxxx】群进行申请");
    }

    @Listen(MsgGetTypes.privateMsg)
    @Filter(value = "!warning", keywordMatchType = KeywordMatchType.CONTAINS)
    public void getWarning(MsgGet msgGet, MsgGetTypes msgGetTypes, MsgSender msgSender, GroupMsg msgGroup) {
        if (!"2308941253".equals(msgGroup.getQQ())) {
            return;
        }
        String jsonString = msgGet.getMsg().replace("!warning", "").replaceAll(",$", "").replace("\\", "");
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.fromObject(jsonString);
        } catch (Exception e) {
            msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "识别错误");
            log.error(e.getMessage(), e);
            log.error(jsonString);
            return;
        }
        boolean remove = false;
        if (jsonObject.containsKey("type")) {
            remove = "erase".equals(jsonObject.getString("type").trim());
        }
        String note = jsonObject.getString("note");
        String fromGroup = "";
        String fromQQ = "";
        if (jsonObject.containsKey("fromGroup")) {
            fromGroup = String.valueOf(jsonObject.getLong("fromGroup"));
            if (remove) {
                insertBanHisotry(fromGroup, true);
                deleteGroupBanList(fromGroup);
                msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已经识别成功，移除黑名单群: " + fromGroup);
            } else {
                insertGroupBanList(fromGroup, "2694900224", note);
                msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已经识别成功，群: " + fromGroup);
            }
        }
        if (jsonObject.containsKey("fromQQ") && jsonObject.getLong("fromQQ") != 0) {
            fromQQ = String.valueOf(jsonObject.getLong("fromQQ"));
            if (remove) {
                insertBanHisotry(fromQQ, false);
                deleteQqBanList(fromQQ);
                msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已经识别成功，移除黑名单人员: " + fromQQ);
            } else {
                insertQqBanList(fromQQ, "2694900224", note);
                msgSender.SENDER.sendGroupMsg(msgGroup.getGroupCode(), "已经识别成功，人员: " + fromQQ);
            }
        }
    }
}
